var log = new LOG();

var currentSiteId;
var speed = 1;
var counter = 2;
var toggle = false;
var periodePic = 4000; // msec until picture background change
var timerGalerie;
var resolution;
var kontaktOk = true;
var clickMenuOk = true;

var backImgArray = new Array( "b1.jpg", "b2.jpg" );

$( document ).ready( function() {
   log.setLevel( "debug" );
   log.trace( "DOM loaded" );

   jQuery.fx.interval = 20;

   getBackPics();

   currentSiteId = 0;

   start( false );

   $( '#menu li' ).click( function() {

      var siteId = parseInt( $( this ).attr( "data-siteId" ) );
      log.trace( "new siteId requested= " + siteId );
      if (currentSiteId == siteId) {
         return;
      }
      clickMenuOk = false;
      menuClickContent( siteId );
   } );
   /*
    * $('').click(function(){ menuClickContent(1); });
    * 
    * $('#con5link').click(function(){ $.get("content/impressum.html",
    * function(data, status){ $("#con5Box").html(data); log.debug("Ajax loaded
    * Impressum."); log.trace("Data: " + data); log.trace("Status: " + status); },
    * "html"); menuClickContent(5); });
    */

   $( '#kontaktButton' ).click( function() {
      sendKontaktFormular();
   } );

   $( '#kontaktButtonReset' ).click( function() {
      clearKontaktFormular();
   } );

   $( '#menuTab' ).click( function() {
      $( '#menu' ).toggle( 500 );
   } );

   document.addEventListener( 'contextmenu', function( ev ) {
      ev.preventDefault();
      return false;
   } );

} );

function start( alreadyLoaded ) {

   $( '#home2' ).css( "z-index", "-999" );
   $( '#home2' ).css( 'opacity', 0 );

   $( '#home2' ).css( 'background-image', 'url("./pic/backGalerie/' + backImgArray[1] + '")' );

   if (alreadyLoaded) {
      $( '#home1' ).css( "z-index", "-999" );
      $( '#home1' ).css( 'background-image', 'url("./pic/backGalerie/' + backImgArray[0] + '")' );
      toggle = false;
      counter = 2;

      $( '#home1' ).css( 'opacity', 0 ).animate( {
         opacity : 1
      }, 1000, function() {
         currentSiteId = 0;
         klickMenuOk = true;
         timerGalerie = window.setInterval( changeImg, periodePic );
      } );

   }

   else {
      $( '#welcome' ).css( 'top', window.innerHeight / 6 );
      $( '#welcome' ).css( 'font-size', window.innerWidth / 12 );

      $( '#welcome' ).animate( {
         opacity : 1
      }, 500 ).delay( 500 ).animate( {
         opacity : 0
      }, 500, function() {
         removeTag( document.getElementById( 'welcome' ) );
         $( '#menu' ).animate( {
            opacity : 1
         }, 1000 );
         $( '#footer' ).animate( {
            opacity : 1
         }, 1000 );
      } );

      $( '#home1' ).delay( 1000 ).animate( {
         opacity : 1
      }, 1000, function() {
         timerGalerie = window.setInterval( changeImg, periodePic );
      } );
   }

}

function changeImg() {
   if (!toggle) {
      $( '#home2' ).animate( {
         opacity : 1
      }, 2000, function() {
         $( '#home1' ).css( "z-index", "-999" );
         $( '#home1' ).css( 'opacity', 0 );
         $( '#home2' ).css( "z-index", "-1001" );
         $( '#home1' ).css( 'background-image', 'url("./pic/backGalerie/' + backImgArray[counter] + '")' );
      } );
   } else {

      $( '#home1' ).animate( {
         opacity : 1
      }, 2000, function() {
         $( '#home2' ).css( "z-index", "-999" );
         $( '#home2' ).css( 'opacity', 0 );
         $( '#home1' ).css( "z-index", "-1001" );
         $( '#home2' ).css( 'background-image', 'url("./pic/backGalerie/' + backImgArray[counter] + '")' );
      } );
   }
   currentPic = $( '#home1' );
   counter++;

   if (counter >= backImgArray.length)
      counter = 0;

   toggle = !toggle;

}

function removeTag( tag ) {
   tag.parentNode.removeChild( tag );
}

function menuClickHome() {
   if (currentSiteId == 0)
      return;

   $( '#con' + currentSiteId + 'Box' ).stop( true, false ).css( 'opacity', 0 );
   $( '#con' + currentSiteId + 'Box' ).css( 'z-index', '-1001' );
   $( '#con' + currentSiteId + 'Box' ).css( 'display', 'none' );
   $( '#' + currentSiteId + 'Box' ).css( 'display', 'block' );

   $( '#con' + currentSiteId + "link a" ).css( 'color', '' );

   // $('#con0link a').css('color', menueColor);
   $( '#con' + currentSiteId + "link" ).addClass( "notSelected" );
   $( '#con' + currentSiteId + "link" ).removeClass( "selected" );

   $( '#con0link' ).addClass( "selected" );
   $( '#con0link' ).removeClass( "notSelected" );

   removeGalerie( currentSiteId + 2 );
   currentSiteId = 0;

   currentPic = 1;

   setWidth();

   start( true );

   if ($( '#menuTab' ).is( ":visible" ))
      $( '#menu' ).css( "display", "none" );

}

function menuClickContent( newSiteId ) {

   // if(currentSiteId == newSiteId){
   // clickMenuOk = true;
   // return;
   // }

   if ($( '#menuTab' ).is( ":visible" ))
      $( '#menu' ).css( "display", "none" );

   if (currentSiteId > 0) {
      // old was not home site
      $( '.backImg[data-siteId=' + currentSiteId + ']' ).stop( true, false ).css( "z-index", "-1001" );
   } else {
      // old site was home site
      $( '#home1' ).stop( true, false ).css( "z-index", "-1001" ).css( "z-index", "-1001" );
      $( '#home2' ).stop( true, false ).css( "z-index", "-1001" ).css( "z-index", "-1001" );
      window.clearTimeout( timerGalerie );
   }

   if (newSiteId == 0) {
      $( '.backImg[data-siteId=' + currentSiteId + ']' ).css( "opacity", 0 );
      start( true );
      return;
   }

   $( 'html, body' ).animate( {
      scrollTop : '0px'
   }, 100 );

   $( '.backImg[data-siteId=' + newSiteId + ']' ).css( "z-index", "999" ).animate( {
      opacity : 1
   }, 1000, function() {

      if (currentSiteId > 0) {
         $( '.backImg[data-siteId=' + currentSiteId + ']' ).css( "opacity", 0 );
      } else {
         $( '#home1' ).css( "opacity", 0 );
         $( '#home2' ).css( "opacity", 0 );
      }

      currentSiteId = newSiteId;
      clickMenuOk = true;
   } );

}

function sendKontaktFormular() {

   if (!kontaktOk)
      return;
   kontaktOk = false;

   var vorname = $( '#kontaktInputVorname' ).val();
   var nachname = $( '#kontaktInputNachname' ).val();
   var email = $( '#kontaktInputEmail' ).val();
   var nachricht = $( '#MitteilungInput' ).val();

   $( '#kontaktInputVorname' ).css( "border-color", "black" );
   $( '#kontaktInputNachname' ).css( "border-color", "black" );
   $( '#kontaktInputEmail' ).css( "border-color", "black" );
   $( '#MitteilungInput' ).css( "border-color", "black" );

   if (vorname == '' || nachname == '' || email == '' || nachricht == '') {
      var errorMessage = "Fehler! Folgende Felder fehlen noch:\n";
      if (vorname == '') {
         errorMessage += "Vorname\n";
         $( '#kontaktInputVorname' ).css( "border-color", "red" );
      }
      if (nachname == '') {
         errorMessage += "Nachname\n";
         $( '#kontaktInputNachname' ).css( "border-color", "red" );
      }
      if (email == '') {
         errorMessage += "Email\n";
         $( '#kontaktInputEmail' ).css( "border-color", "red" );
      }
      if (nachricht == '') {
         errorMessage += "Nachricht\n";
         $( '#MitteilungInput' ).css( "border-color", "red" );
      }
      console.log( errorMessage );

      $( '#errorKontakt h1' ).css( "color", "rgb(255, 0, 0)" );
      $( '#errorKontakt h1' ).html( "Bitte fehlende Felder ausf&uuml;llen!" );

      $( '#errorKontakt' ).stop( true, true ).animate( {
         opacity : 1
      }, 500 ).animate( {
         opacity : 0
      }, 500 ).animate( {
         opacity : 1
      }, 500 ).animate( {
         opacity : 0
      }, 500 ).animate( {
         opacity : 1
      }, 500 ).animate( {
         opacity : 0
      }, 500 ).animate( {
         opacity : 1
      }, 500, function() {
         kontaktOk = true;
      } );
   } else {
      if (!isValidEmailAddress( email )) {
         $( '#kontaktInputEmail' ).css( "border-color", "red" );
         console.log( unescape( "Email %FCberpr%FCfen! Bitte korrigieren." ) );
         $( '#errorKontakt h1' ).html( "Email-Adresse ung&uuml;ltig! Bitte korrigieren." );
         $( '#errorKontakt h1' ).css( "color", "rgb(255, 0, 0)" );

         $( '#errorKontakt' ).stop( true, true ).animate( {
            opacity : 1
         }, 500 ).animate( {
            opacity : 0
         }, 500 ).animate( {
            opacity : 1
         }, 500 );
      } else {

         var xmlhttp;
         if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
         } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );
         }
         xmlhttp.onreadystatechange = function() {

            if (xmlhttp.readyState == 4) {
               switch (xmlhttp.status) {
                  case 200:
                     console.log( "AJAX Response: " + xmlhttp.responseText );
                     if (parseInt( xmlhttp.responseText ) == 1) {

                        $( '#kontaktInputVorname' ).css( "border-color", "green" );
                        $( '#kontaktInputNachname' ).css( "border-color", "green" );
                        $( '#kontaktInputEmail' ).css( "border-color", "green" );
                        $( '#MitteilungInput' ).css( "border-color", "green" );

                        $( '#errorKontakt h1' ).css( "color", "rgb(0, 150, 0)" );
                        $( '#errorKontakt h1' ).html( "Erfolgreich gesendet!" );

                        $( '#errorKontakt' ).stop( true, true ).animate( {
                           opacity : 1
                        }, 500 ).delay( 3000 ).animate( {
                           opacity : 0
                        }, 500, function() {
                           $( '#errorKontakt h1' ).css( "color", "rgb(255, 0, 0)" );
                           clearKontaktFormular();
                        } );
                     } else {
                        $( '#errorKontakt h1' ).css( "color", "rgb(255, 0, 0)" );
                        $( '#errorKontakt h1' ).html( "Server meldet Fehler. Bitte erneut versuchen!" );
                        $( '#errorKontakt' ).stop( true, true ).animate( {
                           opacity : 1
                        }, 500 ).delay( 3000 ).animate( {
                           opacity : 0
                        }, 500, function() {
                           clearKontaktFormular();
                        } );
                     }

                     break;
                  case 404:
                     console.log( "Error 404: Server unerreichbar!" );
                     kontaktOk = true;
                     break;
                  default:
                     kontaktOk = true;
                     break;
               }
            }

         }

         xmlhttp.open( "POST", "http://ds-photography.info/messages/interface.php", true );
         xmlhttp.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
         xmlhttp.send( "vorname=" + vorname + "&nachname=" + nachname + "&email=" + email + "&nachricht=" + nachricht );

      }
   }

}

function clearKontaktFormular() {

   $( '#kontaktInputVorname' ).val( "" );
   $( '#kontaktInputNachname' ).val( "" );
   $( '#kontaktInputEmail' ).val( "" );
   $( '#MitteilungInput' ).val( "" );

   $( '#kontaktInputVorname' ).css( "border-color", "black" );
   $( '#kontaktInputNachname' ).css( "border-color", "black" );
   $( '#kontaktInputEmail' ).css( "border-color", "black" );
   $( '#MitteilungInput' ).css( "border-color", "black" );

   $( '#errorKontakt' ).css( "opacity", 0 );
   kontaktOk = true;

}

function getBackPics() {

   var xmlhttp;
   if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
   } else {
      // code for IE6, IE5
      xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );
   }
   xmlhttp.onreadystatechange = function() {

      if (xmlhttp.readyState == 4) {
         switch (xmlhttp.status) {
            case 200:

               var doc = StringtoDOM( xmlhttp.responseText );
               console.log( doc );

               var pics = doc.getElementsByTagName( "pic" );

               if (pics.length == 0) {
                  console.log( "Server meldet Fehler. Konnte keine BackGalerie-Bilder laden!" );
                  return;
               }

               for (var i = 1; i < pics.length; i++) {
                  backImgArray[i] = doc.getElementsByTagName( "pic" )[i].innerHTML;
               }

               $( '#home2' ).css( "z-index", "-999" );
               $( '#home2' ).css( 'opacity', 0 );
               $( '#home2' ).css( 'background-image', 'url("./pic/backGalerie/' + backImgArray[1] + '")' );

               break;
            case 404:
               console.log( "Error 404: Server unerreichbar!" );
               break;
            default:
               break;
         }
      }
   }

   xmlhttp.open( "POST", "picUpload/index.php", true );
   xmlhttp.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
   xmlhttp.send( "ordnerPic=" + "backGalerie" );

}

function getGaleriePics() {

   var xmlhttp;
   if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
   } else {
      // code for IE6, IE5
      xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );
   }
   xmlhttp.onreadystatechange = function() {

      if (xmlhttp.readyState == 4) {
         switch (xmlhttp.status) {
            case 200:

               var doc = StringtoDOM( xmlhttp.responseText );
               console.log( doc );

               var pics = doc.getElementsByTagName( "pic" );

               if (pics.length == 0) {
                  console.log( "Server meldet Fehler. Konnte keine Galerie-Bilder laden!" );
                  return;
               }

               for (var i = 0; i < pics.length; i++) {
                  galerieBilder[i] = "pic/galerieBilder/" + doc.getElementsByTagName( "pic" )[i].innerHTML;
               }

               ladeGalerieBilder();

               $( ".galerieBildLazy" ).unveil( 200, function() {
                  $( this ).load( function() {
                     $( this ).animate( {
                        opacity : 1
                     }, 1000 );
                  } );
               } );

               $( "#inhalt1 img" ).click( function( event ) {

                  $( "body" ).css( "overflow", "hidden" );

                  var overlay = document.createElement( "div" );
                  overlay.setAttribute( "class", "overlay" );

                  var picViewPanel = document.createElement( "div" );
                  picViewPanel.setAttribute( "class", "picViewPanel" );

                  var pic = document.createElement( "img" );
                  pic.setAttribute( "id", "picViewpic" );

                  var linkS = event.target.src.replace( "galerieBilder", "downloadBilder" );

                  pic.setAttribute( "src", linkS );

                  var closePic = document.createElement( "img" );
                  closePic.setAttribute( "id", "closePic" );
                  closePic.setAttribute( "src", "img/close.png" );

                  picViewPanel.appendChild( pic );
                  picViewPanel.appendChild( closePic );

                  overlay.appendChild( picViewPanel );
                  document.getElementsByTagName( "body" )[0].appendChild( overlay );
                  $( ".overlay" ).stop( true, false ).animate( {
                     opacity : 1
                  }, 500 );

                  $( '#picViewpic' ).hover( function() {
                     $( "#closePic" ).animate( {
                        opacity : 1
                     }, 500 );
                  }, function() {
                     if ($( '#closePic:hover' ).length == 0) {
                        $( "#closePic" ).animate( {
                           opacity : 0
                        }, 500 );
                     }
                  } );

                  $( '.overlay' ).click( function() {
                     $( this ).stop( true, false ).animate( {
                        opacity : 0
                     }, 500, function() {
                        $( this ).remove();
                     } );
                     $( "body" ).css( "overflow", "auto" );
                  } );

               } );

               /*
                * ladeDownloadBilder();
                * 
                * $(".downloadBildLazy").unveil(200, function() {
                * $(this).load(function() { $(this).animate({opacity:1}, 500);
                * }); });
                */

               break;
            case 404:
               console.log( "Error 404: Server unerreichbar!" );
               break;
            default:
               break;
         }
      }
   }

   xmlhttp.open( "POST", "picUpload/index.php", true );
   xmlhttp.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
   xmlhttp.send( "ordnerPic=" + "galerieBilder" );

}

function ladeGalerieBilder() {
   for (var i = 0; i < galerieBilder.length; i++) {
      var neuBild = document.createElement( "img" );

      var linkS = galerieBilder[i];

      if (i < 3) {
         neuBild.setAttribute( "class", "galerieBild" );
         neuBild.setAttribute( "src", linkS ); // dateiname + s ist die small
         // version des Bildes
      } else {
         neuBild.setAttribute( "data-src", linkS ); // dateiname + s ist die
         // small version des
         // Bildes
         neuBild.setAttribute( "src", "img/loader.gif" );
         neuBild.setAttribute( "class", "galerieBildLazy" );
      }
      document.getElementById( 'inhalt1' ).appendChild( neuBild );
   }
}

/*
 * function ladeDownloadBilder(){
 * 
 * for(var i = 0; i < galerieBilder.length; i++){
 * 
 * var neuBild = document.createElement("img");
 * 
 * if(3 < 6){ neuBild.setAttribute("src" , galerieBilder[i]);
 * neuBild.setAttribute("class", "downloadBild"); } else{
 * neuBild.setAttribute("data-src" , galerieBilder[i]);
 * neuBild.setAttribute("src" , "pic/loader.gif"); neuBild.setAttribute("class",
 * "downloadBildLazy"); } var bildLink = document.createElement("a");
 * 
 * bildLink.setAttribute("href" ,
 * galerieBilder[i].replace("galerieBilder","downloadBilder"));
 * 
 * bildLink.setAttribute("target" , "_blank");
 * 
 * bildLink.appendChild(neuBild);
 * document.getElementById('inhalt2').appendChild(bildLink); } }
 */

function isValidEmailAddress( emailAddress ) {
   var emailRegex = new RegExp( /^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$/i );
   var valid = emailRegex.test( emailAddress );
   return valid;
}

function StringtoDOM( text ) {
   var doc;

   if (window.ActiveXObject) {
      doc = new ActiveXObject( 'Microsoft.XMLDOM' );
      doc.async = 'false';
      doc.loadXML( text );
   } else {
      var parser = new DOMParser();
      doc = parser.parseFromString( text, 'text/xml' );
   }

   return doc;
}
